package ai.esc.speedy.admin.user.infrastructure.jwt;

import ai.esc.speedy.admin.user.api.AppUser;
import ai.esc.speedy.admin.user.infrastructure.shiro.SecurityConsts;
import ai.esc.speedy.common.base.Message;
import ai.esc.speedy.common.util.RedisUtil;
import ai.esc.speedy.common.valueobject.Extend;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.axonframework.common.jpa.EntityManagerProvider;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * @author Rubin
 * @version v1 2020/2/27 16:37
 */
@Slf4j
@Component
public class JwtFilter extends BasicHttpAuthenticationFilter {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private EntityManagerProvider entityManagerProvider;

    private EntityManager getEntityManager() {
        return entityManagerProvider.getEntityManager();
    }

    /**
     * 检测Header里Authorization字段
     * 判断是否登录
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader(SecurityConsts.REQUEST_AUTH_HEADER);
        return authorization != null;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(SecurityConsts.REQUEST_AUTH_HEADER);

        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }


    /**
     * 执行登录认证
     * <p>
     * 这里我们详细说明下为什么最终返回的都是true，即允许访问
     * 例如我们提供一个地址 GET /article
     * 登入用户和游客看到的内容是不同的
     * 如果在这里返回了false，请求会被直接拦截，用户看不到任何东西
     * 所以我们在这里返回true，Controller中可以通过 subject.isAuthenticated() 来判断用户是否登入
     * 如果有些资源只有登入用户才能访问，我们只需要在方法上面加上 @RequiresAuthentication 注解即可
     * 但是这样做有一个缺点，就是不能够对GET,POST等请求进行分别过滤鉴权(因为我们重写了官方的方法)，但实际上对应用影响不大
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttempt(request, response)) {
            try {
                this.executeLogin(request, response);
            } catch (Exception e) {

                String msg = e.getMessage();
                Throwable throwable = e.getCause();

                if (throwable instanceof SignatureVerificationException) {
                    msg = "Token或者密钥不正确(" + throwable.getMessage() + ")";

                } else if (throwable instanceof TokenExpiredException) {

                    log.info("AccessToken已过期，刷新ing...");
                    if (this.refreshToken(request, response)) {
                        return true;
                    } else {
                        msg = "Token已过期(" + throwable.getMessage() + ")";
                    }

                } else {
                    if (throwable != null) {
                        msg = throwable.getMessage();
                    }
                }
                this.response401(request, response, msg);
                return false;
            }
        }
        return true;
    }


    /**
     * // todo 需要用定时任务去更新RefreshToken？
     * 刷新AccessToken，进行判断RefreshToken是否过期，未过期就返回新的AccessToken且继续正常访问
     *
     * @param request
     * @param response
     * @return
     */
    private boolean refreshToken(ServletRequest request, ServletResponse response) {
        // 获取Token
        String token = this.getAuthzHeader(request);
        String tokenLastPart = token.substring(token.lastIndexOf("."));
        String refreshTokenCacheKey = SecurityConsts.PREFIX_SHIRO_REFRESH_TOKEN + tokenLastPart;
        // 判断Redis中RefreshToken是否存在
        if (redisUtil.exists(refreshTokenCacheKey)) {
            String refreshToken = redisUtil.get(refreshTokenCacheKey).toString();
            // 获取账号
            String account = jwtUtil.getClaim(refreshToken, SecurityConsts.ACCOUNT);

            // 查找App用户信息
            TypedQuery<AppUser> appUserTypedQuery = getEntityManager()
                    .createNamedQuery("AppUser.findByAccount", AppUser.class);
            appUserTypedQuery.setParameter("account", account);
            Optional<AppUser> optionalAppUser = appUserTypedQuery.getResultStream().findAny();

            if (optionalAppUser.isPresent()) {
                AppUser appUser = optionalAppUser.get();
                JwtUserInfo userInfo = new JwtUserInfo(account,
                        appUser.getUserId(),
                        Objects.requireNonNull(appUser.getData()).getExtendData(),
                        appUser.getPassportId()
                );
                try {
                    // 新AccessToken
                    token = jwtUtil.sign(userInfo);
                } catch (Exception e) {
                    log.error("刷新token时，新建token错误！" + e.getLocalizedMessage());
                }

                // 使用AccessToken 再次提交给ShiroRealm进行认证，如果没有抛出异常则登入成功，返回true
                JwtToken jwtToken = new JwtToken(token);
                this.getSubject(request, response).login(jwtToken);

                // 设置响应的Header头新Token
                HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                httpServletResponse.setHeader(SecurityConsts.REQUEST_AUTH_HEADER, token);
                httpServletResponse.setHeader("Access-Control-Expose-Headers", SecurityConsts.REQUEST_AUTH_HEADER);
                return true;
            }
        }
        return false;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 401非法请求
     *
     * @param request
     * @param response
     */
    private void response401(ServletRequest request, ServletResponse response, String msg) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        // httpServletResponse.sendRedirect("/401");
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = httpServletResponse.getWriter()) {
            out.append(Message.builder().error(msg).build().toJsonStr());
        } catch (IOException e) {
            log.error("返回Response信息出现IOException异常:" + e.getMessage());
        }
    }

}